#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_tim.h"

void PWMInit(void)
{
    GPIO_InitTypeDef gpioInitStruct;
    TIM_TimeBaseInitTypeDef timeInitStruct;
    TIM_OCInitTypeDef timeOcInitStruct;

    RCC_AHB1PeriphClockCmd(RCC_AHB1ENR_GPIOAEN, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1ENR_TIM3EN, ENABLE);

    GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_TIM3);
    gpioInitStruct.GPIO_Mode = GPIO_Mode_AF;
    gpioInitStruct.GPIO_OType = GPIO_OType_PP;
    gpioInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    gpioInitStruct.GPIO_Pin = GPIO_Pin_7;
    GPIO_Init(GPIOA, &gpioInitStruct);

    timeInitStruct.TIM_Period = 665/*9999*/;
    timeInitStruct.TIM_Prescaler = 3;
    timeInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
    timeInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM3, &timeInitStruct);

    timeOcInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
    timeOcInitStruct.TIM_OutputState = TIM_OutputState_Enable;
    timeOcInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OC2Init(TIM3, &timeOcInitStruct);

    TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

    TIM_Cmd(TIM3, ENABLE);
}

void PWMSetCmp(u32 cmp)
{
    TIM_SetCompare2(TIM3, cmp);
}
